import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_switch.dart';
import 'package:rxdart/rxdart.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/mode/base_mode.dart';
import 'package:loxen/mode/mine/user_privacy.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';

class PrivacyPolicyWidget extends StatelessWidget {
  Widget _item(String tag, bool open,
      {Function(ValueNotifier<bool> notifier, bool select) onChange}) {
    ValueNotifier<bool> select = ValueNotifier(open);
    return ValueListenableProvider.value(
      value: select,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(left: 37.w, right: 34.w),
            width: double.infinity,
            height: 50.h,
            child: Row(
              children: <Widget>[
                Expanded(
                    child: Text(
                  tag,
                  style: TextStyle(fontSize: 28.sp, color: Color(0xFF696C72)),
                )),
                Builder(
                  builder: (BuildContext context) {
                    return MySwitch(
                        activeColor: Theme.of(context).primaryColor,
                        value: context.watch<bool>(),
                        onChanged: (value) {
                          if (onChange != null) onChange.call(select, value);
                        });
                  },
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 37.w, top: 30.h),
            child: Container(
              width: double.infinity,
              height: 1.h,
              color: Color(0xFFEBECF1),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) {
        return _MyViewModel();
      },
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Builder(
              builder: (context) => Container(
                    color: Theme.of(context).backgroundColor,
                    child: SafeArea(
                      child: Row(
                        children: <Widget>[
                          MySubassembly.getBackIcon(context,
                              color:
                                  Theme.of(context).textTheme.subtitle2.color),
                          Expanded(
                            child: Center(
                              child: Text(
                                StringResources.yin_si_ce_lue,
                                style: TextStyle(
                                    fontSize: 32.sp,
                                    color: Theme.of(context)
                                        .textTheme
                                        .subtitle2
                                        .color,
                                ),
                              ),
                            ),
                          ),
                          MySubassembly.getSearchIcon(null,
                              text: Constants.empty)
                        ],
                      ),
                    ),
                  )),
        ),
        body: Builder(
          builder: (BuildContext context) {
            BaseState state = context
                .select<_MyViewModel, BaseState>((value) => value.mState);
            if (state == BaseState.LOADING) {
              return LoadingWidget();
            }
            if (state == BaseState.FAIL) {
              return FailWidget(
                onClick: () {
                  context.read<_MyViewModel>().loadData();
                },
              );
            }
            if (state == BaseState.EMPTY) {
              return EmptyWidget();
            }
            var data = context.watch<_MyViewModel>().userPrivacy;
            return Container(
              decoration: BoxDecoration(
                border: Border(top: BorderSide(
                    width: 1.h,
                    color: Color(0xFFEBECF1)
                )),
                color: Theme.of(context).backgroundColor,
              ),
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(top: 78.h),
                    child:
                        _item('隐藏点赞信息', data.likes, onChange: (notifier, select) {
                      Provider.of<_MyViewModel>(context, listen: false).setLikes(
                          select,
                          onSuccess: () => notifier.value = select,
                          onError: (msg) => Toast.show(msg, context));
                    }),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 30.h),
                    child: _item('隐藏评论信息', data.comment,
                        onChange: (notifier, select) {
                      Provider.of<_MyViewModel>(context, listen: false)
                          .setComment(select,
                              onSuccess: () => notifier.value = select,
                              onError: (msg) => Toast.show(msg, context));
                    }),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}

class _MyViewModel extends BaseViewModel {
  UserPrivacy userPrivacy;

  _MyViewModel() {
    loadData();
  }

  void setLikes(bool likes,
      {Function() onSuccess, Function(String error) onError}) {
    ApiService.setUserPrivacy(null, likes).listen((event) {
      if (event.statusCode == 200) {
        if (onSuccess != null) onSuccess.call();
      } else {
        if (onError != null) onError.call('隐私设置失败');
      }
    }, onError: (error, stack) {
      print(error);
      print(stack);
      if (onError != null) onError.call(error.toString());
    });
  }

  void setComment(bool comment,
      {Function() onSuccess, Function(String error) onError}) {
    ApiService.setUserPrivacy(comment, null).listen((event) {
      if (event.statusCode == 200) {
        if (onSuccess != null) onSuccess.call();
      } else {
        if (onError != null) onError.call('隐私设置失败');
      }
    }, onError: (error, stack) {
      print(error);
      print(stack);
      if (onError != null) onError.call(error.toString());
    });
  }

  void loadData() {
    ApiService.userPrivacy()
        .doOnListen(() {
          mState = BaseState.LOADING;
          notifyListeners();
        })
        .flatMap((value) => compute(decodeMode, value.data).asStream())
        .flatMap((value) => Stream.value(value.data))
        .listen((event) {
          if (event != null) {
            userPrivacy = event;
            mState = BaseState.CONTENT;
          } else {
            mState = BaseState.EMPTY;
          }
        }, onError: (error, stack) {
          mState = BaseState.FAIL;
        }, onDone: () => notifyListeners());
  }

  static BaseMode<UserPrivacy> decodeMode(dynamic json) {
    return BaseMode<UserPrivacy>(json);
  }
}

class MyBotton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 120.w,
      height: 50.h,
      decoration: BoxDecoration(
          color: Theme.of(context).primaryColor,
          borderRadius: BorderRadius.all(Radius.circular(50.w))),
      child: CustomPaint(
        size: Size(50.h, 50.h),
        painter: MyAction(),
      ),
    );
  }
}

class MyAction extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.fill //填充
      ..color = Colors.white;

    canvas.drawCircle(Offset(25.h, 25.h), 23.h, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
